﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TableProto;

public class GameLoader : MonoSingleton<GameLoader> {

	public delegate void LoadProgressDelegate(float progress);

	public delegate void LoadCompleteDelegate();

	private GameLoader.LoadProgressDelegate LoadProgressEvent;

	private GameLoader.LoadCompleteDelegate LoadCompleteEvent;

	public bool isLoadStart;

	private int _nProgress;

	private Coroutine m_handle_CoroutineLoad;

	protected override void Init ()
	{
		base.Init ();
	}

	public void ResetLoader()
	{
		this._nProgress = 0;
		if (this.isLoadStart)
		{
			StopCoroutine (this.m_handle_CoroutineLoad);
			this.isLoadStart = false;
		}
			
	}

	/// <summary>
	/// 开始加载数据
	/// </summary>
	/// <param name="progress">Progress.</param>
	/// <param name="finish">Finish.</param>
	public void Load(GameLoader.LoadProgressDelegate progress, GameLoader.LoadCompleteDelegate finish)
	{
		if (this.isLoadStart)
		{
			return;
		}
		this.LoadProgressEvent = progress;
		this.LoadCompleteEvent = finish;
		this._nProgress = 0;
		this.isLoadStart = true;
		this.m_handle_CoroutineLoad = StartCoroutine(this.CoroutineLoad());
	}

	private IEnumerator CoroutineLoad() {
        //Debug.LogError(1);
		TableProtoManager.Instance.PreLoadTableData ();
		yield return new WaitForEndOfFrame ();
#if !PACKAGE_ENGLISH
        yield return PrepareScene();
#endif
        //预加载部分对象池资源
        UpdateProgress(0);
#if !PACKAGE_ENGLISH
        yield return PrepareActor ();
#endif
        if (this.LoadCompleteEvent != null) {
			this.LoadCompleteEvent ();
		}
	}

	private IEnumerator PrepareActor() {
		yield return new WaitForEndOfFrame();
		Dictionary<uint, ActorInfo> SceneRes = TableProtoLoader.ActorInfoDict;
		int proCount = 1000 / SceneRes.Count;
		int prore = 1000 % SceneRes.Count;
		foreach (ActorInfo info in SceneRes.Values) {
			GameObjectPool.Instance.PrepareGameObject (info.res_path, enResourceType.ScenePrefab, 1);
			yield return new WaitForEndOfFrame();
			UpdateProgress(proCount);
		}
		yield return new WaitForEndOfFrame();
		UpdateProgress(prore);
	}

    private IEnumerator PrepareScene()
    {
        yield return new WaitForEndOfFrame();
        GameObjectPool.Instance.PrepareGameObject(SceneObjManger.ScenePath(SceneObjManger.MAIN_CONTROLLER), enResourceType.ScenePrefab, 1);
        GameObjectPool.Instance.PrepareGameObject(SceneObjManger.MAIN_SHADOW, enResourceType.ScenePrefab, 1);
    }

	private void UpdateProgress(int addProgress) {
		this._nProgress += addProgress;
		if (this.LoadProgressEvent != null) {
			this.LoadProgressEvent (this._nProgress / 1000f);
		}
	}
}
